package com.gitee.feizns.quickstart.ding.talk.event.contacts;

import com.dingtalk.api.response.OapiV2UserGetResponse;
import com.dingtalk.open.app.api.GenericEventListener;
import com.dingtalk.open.app.api.message.GenericOpenDingTalkEvent;
import com.dingtalk.open.app.stream.protocol.event.EventAckStatus;
import com.gitee.feizns.quickstart.ding.talk.api.top.api.v2.user.Get;
import com.gitee.feizns.quickstart.ding.talk.api.v10.oauth2.AccessToken;
import lombok.RequiredArgsConstructor;

import java.util.List;
import java.util.function.BiConsumer;

/**
 * 用户新增事件
 * @author feizns
 * @since 2025/3/24
 */
@RequiredArgsConstructor
public class UserAddOrgListener implements GenericEventListener {

    /**
     * 访问令牌
     */
    private final AccessToken accessToken;

    /**
     * 处理
     */
    private final BiConsumer<String, OapiV2UserGetResponse.UserGetResponse> handler;

    @Override
    public EventAckStatus onEvent(GenericOpenDingTalkEvent event) {
        return onEvent(event, accessToken, handler);
    }

    public static EventAckStatus onEvent(GenericOpenDingTalkEvent event,
                                         AccessToken accessToken,
                                         BiConsumer<String, OapiV2UserGetResponse.UserGetResponse> handler) {
        if ( "user_add_org".equals(event.getEventType()) ) {
            List<String> userId = event.getData().getList("userId", String.class);
            if ( handler != null )
                userId.forEach(userid -> handler.accept(userid, Get.execute(accessToken.get(), userid)));
        }
        return EventAckStatus.SUCCESS;
    }

}
